package com.lyn.serialPort;

import com.lyn.serialPort.entity.Device;
import com.lyn.serialPort.entity.Driver;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

class SerialPortFinder {
    private static final String DRIVERS_PATH = "/proc/tty/drivers";
    private static final String SERIAL_FIELD = "serial";


    public static List<Device> getDevices() {
        List<Device> devices = new ArrayList<>();
        try {
            List<Driver> drivers = getDrivers();
            for (Driver driver : drivers) {
                List<File> driverDevices = driver.getDevices();
                for (File file : driverDevices) {
                    String devicesName = file.getName();
                    devices.add(new Device(devicesName, driver.name, file));
                }
            }
        } catch (IOException var10) {
            var10.printStackTrace();
        }
        return devices;
    }

    public static Device getDevice(String name) {
        List<Device> devices = getDevices();
        for (Device device : devices) {
            if (device.name.equals(name)) {
                return device;
            }
        }
        return null;
    }

    private static List<Driver> getDrivers() throws IOException {
        List<Driver> drivers = new ArrayList<>();
        LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(DRIVERS_PATH));
        String readLine;
        while ((readLine = lineNumberReader.readLine()) != null) {
            String driverName = readLine.substring(0, 21).trim();
            String[] fields = readLine.split(" +");
            if (fields.length >= 5 && fields[fields.length - 1].equals(SERIAL_FIELD)) {
                drivers.add(new Driver(driverName, fields[fields.length - 4]));
            }
        }
        return drivers;
    }


}
